--[[
    雪月框架
    编译主要模块
]]

---雪月框架编译器
builder = {
    ver = "1.1",
    data = {},
    hook_set = {},
    hook_get = {},

}

setmetatable(builder,
    {
        __index = function (this, key)
            local on_get = this.hook_get[key]
            if on_get then
                return on_get(this, key)
            end
            return this.data[key]
        end,
        __newindex = function (this, key, value)
            local on_set = this.hook_set[key]
            if on_set then
                on_set(this, key, value)
            end
            this.data[key] = value
        end,
    }
)
require 'Mods'

require 'compile.updateW3x'
require 'compile.copyTemp'
require 'compile.injectJass'
require 'compile.xslk.build'
require 'compile.packW3x'

--清理临时的地图
function builder:clearTemp()
    local temp = self.debug
    local list = dir_list( temp , false, '*.w3x' )
    local count = table.len(list)
    local max = 30

    if self.mapcfg._ini.temp then --需要先引用一次 ini 自动创建空表
        max = self.mapcfg._ini.temp.max or 30
    end

    if count >= max then
        for _, value in ipairs(list) do
            delete(temp ..'\\'.. value)
            count = count - 1
            if count < max then
                break
            end
        end
    end
    self.w3x_test = temp .. (list[#list] or '')
end


function builder:build_info()
    print("编译项目:", self.map)
    print("编译方式:", ('%s[%s]'):format( self.type,TYPE[self.type] ) )
    print('----Builer - 执行过程----')
end

--执行编译过程 [入口函数]
function builder:exec( )
    self:build_info()

    self.debug = Root .. '\\debug\\'  ..  self.map
    self.temp = self.debug .. '\\temp'

    self.path_map = Root .. '\\maps\\' .. self.map

    local cfg = self.cfg
    cfg._ini.Builder.LastMap = self.map
    cfg._ini.Builder.LastType = self.type

    if self.type == 'last' then
        self:last()
        print( ('测试最后一次编译的结果 %s ...'):format( self.w3x_test:sub( self.w3x_test:find_r('\\') + 1 ) ) )
    else
        self.mapcfg = ini:open( self.path_map  .. "\\config.ini") --maps\\[project]\\config.ini
        self:clearTemp()
        self:normal()
        cfg._ini.Last.TestMap = self.w3x_test
        print('编译完成,启动测试...')
    end

    self.cfg:save()
    self:LocalTest( self.w3x_test )

end

--常规编译流程
function builder:normal()

    rd( self.temp ) --处理前先清理临时文件

    self:updateTerrainFormW3x() --更新地形图

    self:copyTempProject()  --复制临时项目

    self:jass_inject() --注入jass

    self:xslkBuild()

    xslk.item.mod:inject()

    mod:genCode()   --注入Mod启动代码

    self:packW3x()    --打包地图

    print('删除临时文件...')
    rd( self.temp )
end

---@param mapPath string 地图路径
function builder:LocalTest( mapPath )
    local cmd =   ([[cd /d "%s"&bin\YDWEConfig.exe -launchwar3 -loadfile "%s"]]):format(self.ydPath, mapPath)
    os.execute(cmd)
    --io.popen(cmd):close()
end

---编译上一次地图
function builder:lastBuild()
    local cfg = self.cfg
    --最后的项目
    self.map = cfg._ini.Builder.LastMap
    if not self.map then
        return
    end
    self.type = cfg._ini.Builder.LastType
    --最后的选择的类型
    if not self.type then
        return
    end

    self:exec()
end

---测试上一次地图
function builder:lastTest()
    local cfg = self.cfg
    --最后的项目
    local mapPath = cfg._ini.Last.TestMap
    if not mapPath then
        return
    end

    print('测试上一次测试过的地图...')
    print(mapPath)

    self:LocalTest( mapPath )

end

function builder:last()
    local temp = Root .. '\\debug\\'  ..  self.map
    local list = dir_list( temp ,false, '*.w3x' )
    self.w3x_test = temp .. '\\' .. (list[#list] or ''):a2u()
    self.cfg._ini.Last.TestMap = self.w3x_test
end

function builder:editor(  )
    print( '用编辑器打开',  self.map )
    local map = Root .. '\\maps\\'  ..  self.map .. '\\terrain.w3x'
    local edit_exes = {
        '雪月WE.exe',
        'WorldEdit.exe',
        'YDWE.exe',
        'KKWE.exe',
    }
    local suc

    local cmd = ([[cd /d "%s"&"%s" -loadfile "%s"]])
    for _, exe in ipairs(edit_exes) do
        if file_exist( self.ydPath .. '\\' .. exe ) then
            cmd = cmd:format(self.ydPath, exe , map)
            suc = true
            break
        end
    end

    if suc then
        os.execute(cmd)
    else
        print('未找到编辑器EXE')
    end

end

